package com.snail.controller;

import com.snail.model.dto.RoleAssignPermissionDTO;
import com.snail.model.pojo.SysRole;
import com.snail.response.BaseResponse;
import com.snail.response.ResultUtils;
import com.snail.service.SysRolePermissionService;
import com.snail.service.SysRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @Author 蔡徐坤
 * @Date 2025/7/16 12:40
 * @Description: 菜单控制层 实现菜单的业务接口
 */
@RequestMapping("/role")
@RestController
public class SysRoleController {
    @Autowired
    private SysRoleService roleService;

    @Autowired
    private SysRolePermissionService rolePermissionService;

    /**
     * 创建角色
     */
    @PostMapping("/createRole")
    public BaseResponse<String> createRole(@RequestBody SysRole sysRole) {
        roleService.save(sysRole);
        return ResultUtils.success("创建成功");
    }

    /**
     * 更新角色
     */
    @PostMapping("/updateRole")
    public BaseResponse<String> updateRole(@RequestBody SysRole sysRole) {
        roleService.updateById(sysRole);
        return ResultUtils.success("更新成功");
    }

    /**
     * 删除角色（逻辑删除）
     */
    @DeleteMapping("/deleteRole/{id}")
    public BaseResponse<String> deleteRole(@PathVariable Long id) {
        roleService.removeById(id);
        return ResultUtils.success("删除成功");
    }

    /**
     * 查询所有角色
     */
    @GetMapping("/allRoles")
    public BaseResponse<List<SysRole>> selectAllRoles() {
        List<SysRole> list = roleService.list();
        return ResultUtils.success(list);
    }

    /**
     * 给角色分配权限
     */
    @PostMapping("/addRoleToPermissions")
    public BaseResponse<String> addRoleToPermissions(@RequestBody RoleAssignPermissionDTO request) {
        rolePermissionService.addPermissionsToRole(request.getRoleId(), request.getPermissionIds());
        return ResultUtils.success("权限分配成功");
    }

    /**
     * 查询角色的权限
     */
    @GetMapping("/getPermissions/{roleId}")
    public BaseResponse<List<Long>> getRolePermissions(@PathVariable Long roleId) {
        List<Long> permissionIds = rolePermissionService.getPermissionIdsByRoleId(roleId);
        return ResultUtils.success(permissionIds);
    }

}
